/**
 * 2017年8月1日
 */
package leetcode;

/**
 * @author Alex
 *
 */
class Node {
	int val;
	Node(int val){
		this.val = val;
	}
	public Node next;
	public String toString(){
		return ""+val;
	}
}
public class ReverseNodesKGroup {
	public static void main(String[] args) {
		Node h = new Node(1);
		h.next = new Node(2);
		h.next.next = new Node(3);
		h.next.next.next = new Node(4);
		h.next.next.next.next = new Node(5);
		Node x = reverseKGroup(h,3);
		x.toString();
	}
	public static Node reverseKGroup(Node head,int k){
		if(head == null || head.next == null || k <2){
			return head;
		}
		Node rest = null;
		Node cur = head;
		for(int i=0;i<k;i++){

			if(cur == null){
				rest = head;
				//不够k个
				return head;
			}else{
				cur = cur.next;
			}
		}
		rest = cur;
		Node x = reverseKGroup(rest, k);
		Node pre = head;
		cur = pre.next;
		while(cur!=x){
			Node next = cur.next;
			cur.next = pre != null? pre:x;
			pre = cur;
			cur = next;
		}
		return pre;
		
		
	}
}
